<template>
  <div class="custom-table">
    <!-- 操作区 -->
    <div v-if="showAction" class="action-box">
      <div>
        <slot name="btnbox"></slot>
        <el-button
          size="small"
          v-if="multipleSelection.length"
          plain
          type="danger"
          icon="el-icon-delete"
          @click="$emit('delManay',multipleSelection)"
          >{{ $t("base.delete") }}</el-button
        >

        <el-button
          size="small"
          v-if="btnList.includes('export')"
          plain
          type="warning"
          icon="el-icon-download"
          @click="exportData"
          >{{ $t("base.export") }}</el-button
        >
      </div>
      <div>
        <el-tooltip
          effect="dark"
          :enterable="false"
          v-if="!isCollapse"
          :content="$t('base.closeSearch')"
          placement="top"
        >
          <el-button
            size="small"
            plain
            circle
            v-if="!isCollapse"
            type="default"
            @click="$bus.$emit('toggleSearch', true)"
            icon="el-icon-arrow-up"
          ></el-button>
        </el-tooltip>
        <el-tooltip
          effect="dark"
          :enterable="false"
          v-if="isCollapse"
          :content="$t('base.openSearch')"
          placement="top"
        >
          <el-button
            size="small"
            plain
            circle
            v-if="isCollapse"
            type="default"
            @click="$bus.$emit('toggleSearch', false)"
            icon="el-icon-arrow-down"
          ></el-button>
        </el-tooltip>
        <el-tooltip
          effect="dark"
          :enterable="false"
          :content="$t('base.refresh')"
          placement="top"
        >
          <el-button
            size="small"
            plain
            circle
            type="default"
            icon="el-icon-refresh"
            @click="$emit('refresh')"
          ></el-button>
        </el-tooltip>
        <!-- 列表操作 -->
        <el-popover placement="bottom" width="150" trigger="click">
          <el-button
            size="small"
            plain
            circle
            style="margin-left:9px;"
            type="default"
            slot="reference"
            icon="el-icon-menu"
          ></el-button>
          <el-checkbox-group ref="drag-box" v-model="checkList">
            <div class="check-row" v-for="item in columns" :key="item.label">
              <svg-icon icon-class="drag-drop-fill" />
              <el-checkbox
                @change="change($event, item)"
                :label="item.label"
                :disabled="item.disableCheck"
              >
                {{ item.label }}
              </el-checkbox>
            </div>
          </el-checkbox-group>
        </el-popover>
      </div>
    </div>
    <!-- 表格区域 -->
    <div class="table-bg">
      <el-table
        :data="list"
        border
        row-key="id"
        v-bind="$attrs"
        v-loading="loading"
        @selection-change="multipleSelection=$event"
      >
        <!-- 选中列 -->
        <el-table-column v-if="showCheckbox" type="selection"></el-table-column>
        <!-- 序号列 -->
        <el-table-column
          v-if="showIndex"
          type="index"
          label="#"
        ></el-table-column>
        <!-- 循环列 -->
        <el-table-column
          v-for="(item, index) in finallyColumns"
          :key="index"
          :label="item.label"
          :width="item.width"
          align="item.align || 'left' "
          :show-overflow-tooltip="item.tooltip"
        >
          <template slot-scope="scope">
            <!-- 自定义列 -->
            <slot
              v-if="item.template"
              :name="item.template"
              :row="scope.row"
              :index="scope.$index"
            ></slot>
            <!-- 常规列 -->
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column align="center" v-show="$slots.action" label="操作">
          <template slot-scope="scope">
            <slot name="action" :row="scope.row" :index="scope.$index"></slot>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
import Sortable from 'sortablejs'
export default {
  name: 'CustomTable',
  props: {
    showAction: {
      type: Boolean,
      default: true
    },
    title: String,
    // 显示序号列
    showCheckbox: {
      type: Boolean,
      default: false
    },
    // 显示序号列
    showIndex: {
      type: Boolean,
      default: false
    },
    // 表格数据
    list: {
      type: Array,
      default: () => []
    },
    // 列信息
    columns: {
      type: Array,
      required: true
    },
    // 加载状态
    loading: {
      type: Boolean,
      default: false
    },
    // 按钮组
    btnList: {
      type: Array,
      default: () => ['add']
    }
  },
  data () {
    const checkList = this.columns.map(val => val.label)
    return {
      // 下拉文字
      checkList,
      // 显示的列
      // showColumnsList: [],
      // 是否折叠
      isCollapse: false,
      // 多个
      multipleSelection: []
    }
  },
  computed: {
    finallyColumns () {
      return this.columns.filter(item => {
        return this.checkList.includes(item.label)
      })
    }
  },
  methods: {
    change (state, val) {
      const result = this.columns.find(item => item.label === val.label)
      result.isRowShow = state
      // this.showColumnsList = this.columns.filter(item => item.isRowShow)
    },
    // 导出数据
    exportData () {
      import('@/vendor/Export2Excel').then(async excel => {
        // 1. 准备数据
        let list = []
        if (this.multipleSelection.length) {
          list = JSON.parse(JSON.stringify(this.multipleSelection))
        } else {
          list = JSON.parse(JSON.stringify(this.list))
        }
        // 2. 准备表头数据
        // const headers = {   汉字: '字段名'  }
        const headers = {}
        this.finallyColumns.forEach(item => {
          headers[item.label] = item.prop
        })
        excel.export_json_to_excel({
          header: Object.keys(headers), // 常规表头
          multiHeader: [], // 复杂表头
          merges: [], // 合并
          data: this.formatJson(headers, list), // 表数据
          filename: this.title || '表格数据' // 文件名称
        })
      })
    },
    // 整理表格的数据
    formatJson (headers, rows) {
      return rows.map(item => {
        return Object.keys(headers).map(key => {
          if (typeof item[headers[key]] === 'object') {
            item[headers[key]] = JSON.stringify(item[headers[key]])
          }
          return item[headers[key]]
        })
      })
    }
  },
  // 挂载成功之后
  mounted () {
    this.$bus.$on('toggleSearch', state => {
      this.isCollapse = state
    })
    // 设置拖动配置
    var ops = {
      animation: 1000,
      filter: '.filter',
      onEnd: evt => {
        // 拖动结束
        const newIndex = evt.newIndex // 新位置序号
        const oldIndex = evt.oldIndex // 老位置序号
        const val1 = this.columns[oldIndex]
        const val2 = this.columns[newIndex]
        this.$set(this.columns, oldIndex, val2)
        this.$set(this.columns, newIndex, val1)
      }
    }
    // 初始化
    Sortable.create(this.$refs['drag-box'].$el, ops)
  }
}
</script>
<style lang="scss" scoped>
.action-box {
  display: flex;
  justify-content: space-between;
}
.check-row {
  line-height: 28px;
  font-size: 20px;
  .svg-icon {
    margin-right: 5px;
  }
}
</style>
